package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 获取Class对象
 */
public class GetClass {
//    public static void main1(String[] args) {
//        Student student = new Student();
//        Class c1 = student.getClass();
//        System.out.println(c1);
//    }
//    public static void main2(String[] args) {
//        Student student = new Student();
//        Class c2 = Student.class;
//        System.out.println(c2);
//    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
//        Class<?> c3 = Class.forName("reflect.Student");
//        System.out.println(c3);
        System.out.println("===========");
        //newInstance();
        //getArgsConstructor();
        //getArgs();
    }

    public static void newInstance() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        Class<?> c1 = Class.forName("reflect.Student");
        Student student = (Student) c1.newInstance();
        System.out.println(student);
    }

    public static void getArgsConstructor() throws ClassNotFoundException, NoSuchMethodException,
            InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> c1 = Class.forName("reflect.Student");
        Constructor<?> constructor = c1.getDeclaredConstructor(String.class, Integer.class);
        constructor.setAccessible(true);
        Student student = (Student) constructor.newInstance("李四", 20);
        System.out.println(student);
    }

    public static void getArgs() throws ClassNotFoundException, InstantiationException,
            IllegalAccessException, NoSuchFieldException {
        Class<?> c1 = Class.forName("reflect.Student");
        Student student = (Student) c1.newInstance();
        Field field = c1.getDeclaredField("name");
        field.setAccessible(true);
        field.set(student, "王五");
        System.out.println(student);
    }

    public static void reflectFunction() throws InstantiationException, IllegalAccessException,
            ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
        Class<?> c1 = Class.forName("reflect.Student");
        Student student = (Student) c1.newInstance();

        Method method = c1.getDeclaredMethod("function", String.class);
        method.setAccessible(true);
        method.invoke(student, "反射私有方法");
    }
}
